/*
 * @description:
 * @Author: jhw
 * @Date: 2023-05-22 22:36:24
 * @LastEditors: jhw
 * @LastEditTime: 2024-07-12 16:44:36
 */
/**
 * @description: 并发执行任务
 * @param {Array} tasks 任务列表
 * @param {Number} limit 并发数
 * @return {Promise} Promise
 */

import { defineAsyncComponent, ref } from 'vue';

export const paralleTasks = (tasks: Array<any>, limit: number = 4) => {
  return new Promise((resolve) => {
    if (!tasks.length) {
      resolve(null);
      return;
    }
    let index = 0;
    let finishCount = 0;

    function _run() {
      // 运行下一个任务
      const task = tasks[index++];
      task().then(() => {
        finishCount++;
        // 任务执行完成后，继续执行下一个任务
        if (index < tasks.length) {
          _run();
        } else if (finishCount === tasks.length) {
          // 所有任务执行完成后，返回
          resolve(null);
        }
      });
    }

    for (let i = 0; i < limit && i < tasks.length; i++) {
      _run();
    }
  });
};

/**
 *
 * @description: 用于获取组件实例
 * @param {T} _comp 组件实例
 * @return {InstanceType<T>} 组件实例
 * @example: const comp = useComRef(Form);
 */
export function useComRef<T extends abstract new (...args: any) => any>(_comp: T) {
  return ref<InstanceType<T>>();
}

// 判断是否为空
export const isEmpty = (obj: any) => {
  if (typeof obj === 'undefined' || obj === null || obj === '') {
    return true;
  }
  if (typeof obj === 'number' && isNaN(obj)) {
    return true;
  }
  if (obj instanceof Date && isNaN(Number(obj))) {
    return true;
  }
  if (Array.isArray(obj) && obj.length === 0) {
    return true;
  }
  if (typeof obj === 'object' && Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

// 去除对象中的空值
export const removeEmpty = (obj: any) => {
  if (typeof obj !== 'object') {
    return obj;
  }
  const result: any = {};
  Object.keys(obj).forEach((key) => {
    if (!isEmpty(obj[key])) {
      result[key] = removeEmpty(obj[key]);
    }
  });
  return result;
};

// 接受组件路径，返回一个异步组件
// export const asyncComponent = (path: string) => {
//   return defineAsyncComponent({
//     loader: () => import(`@/${path}`),
//     loadingComponent: defineAsyncComponent({
//       loader: () => import('@/components/Loading/index.vue'),
//     }),
//   });
// };
